#!/bin/bash
# auth tuyb
# time 20250313

# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}


# 取消系统中的变量设置
unset ETCDCTL_ENDPOINTS ETCDCTL_CACERT ETCDCTL_CERT ETCDCTL_KEY

# 获取leader节点
leader=$(ETCDCTL_API=3 etcdctl --endpoints=https://10.242.4.1:2379,https://10.242.4.2:2379,https://10.242.4.3:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key endpoint status | grep true | awk -F ',' '{print $1}')

leader_ip=$(echo "$leader" | awk -F ':' '{print $2}' | awk -F '//' '{print $2}')

# 备份etcd
ETCDCTL_API=3 etcdctl --endpoints="$leader" --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key snapshot save /backup/etcd/etcd-backup-"$leader_ip"-"$(date +%Y%m%d%H%M%S)".db >> /dev/null 2>&1
isgreen "[$(date)] etcd leader: $leader_ip backup">> /backup/k8sbackup.log 2>&1

# 备份集群配置文件
rsync -azu /etc/kubernetes /backup/cluster-config/ >> /dev/null 2>&1
isgreen "[$(date)] cluster-config backup">> /backup/k8sbackup.log 2>&1

# 备份资源文件
rsync -azu /root/k8s-app /backup/resource-config/ >> /dev/null 2>&1
isgreen "[$(date)] resource-config backup">> /backup/k8sbackup.log 2>&1